import axios from "axios";
import { MessageBox, Message, Loading } from "element-ui";
import store from "@/store";
import { getToken, removeToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import configS from "./config";
import { saveAs } from "file-saver";
import { blobValidate, tansParams } from "./onUtils";
import router from "@/router";
/* 全局 Loading */
import { startLoading, endLoading } from "@/plugins/loading";
let downloadLoadingInstance;
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: configS.jBaseURL,
  // baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 600000,
});

// let loadingInstance;
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom && config.custom.loading === true) {
      startLoading();
    }
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["token"] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    endLoading();
    // 未设置状态码则默认成功状态
    const code = res.data.stateCode || res.stateCode || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.message || errorCode["default"];
    if (code === 401) {
      MessageBox.confirm(
        "登录状态已过期，您可以继续留在该页面，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          store.dispatch("LogOut").then(() => {
            // location.href = "#/login";
            router.push("/login");
          });
        })
        .catch(() => {});
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      Message({
        message: msg,
        type: "error",
      });
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      return res.data;
    } else {
      if (res.config.custom && res.config.custom.text) {
        Message({
          message: res.config.custom.text,
          type: "success",
        });
      }
      if (res.data) {
        return res.data;
      }
    }
  },
  (error) => {
    endLoading();
    if (error && error.response && error.response.data) {
      if (error.response.status === 401) {
        removeToken();
        router.push("/login");
        // window.location.href='/login'
      }
      Message({
        message: error.response.data.message,
        type: "error",
        duration: 5 * 1000,
      });
    }

    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(obj) {
  let object = {
    ...obj,
    fileName: obj.fileName || "文件.xls",
    method: obj.method || "POST",
  };
  if (obj.params) {
    object.url = obj.url + "?" + tansParams(obj.params);
    object.params = {};
  }
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return service[object.method](object.url, object.data, {
    responseType: "blob",
    onDownloadProgress: (progressEvent) => {
      // 计算下载进度的百分比
      const percentCompleted = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`下载进度: ${percentCompleted}%`);
    },
  })
    .then(async (data) => {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
        saveAs(blob, object.fileName);
      } else {
        Message.error("无效的会话，或者会话已过期，请重新登录。");
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}
// 请求工具栏
/**
 * 操作类请求
 * requestFn: function request
 * params: 参数
 * message: 弱提示
 **/
export function HandleRequestSubmit(
  requestFn,
  params,
  message = "保存成功",
  listFetchMethod
) {
  startLoading();
  return requestFn(params)
    .then((result) => {
      message && this.$modal.msgSuccess(message);
      return result;
    })
    .finally(() => {
      listFetchMethod && listFetchMethod();
      endLoading();
    });
}
/**
 * 查询类请求
 * requestFn : function request
 * params: 参数
 * setLoading 加载修改状态
 **/
export function HandleRequestQuery(
  requestFn,
  params,
  setLoading,
  listFetchMethod
) {
  setLoading && setLoading(true);
  return requestFn(params).finally(() => {
    listFetchMethod && listFetchMethod();
    setLoading && setLoading(false);
  });
}
export default service;
